package com.fenghuajueli.module_user.network.retrofit

import com.fenghuajueli.libbasecoreui.baseswitch.GeneratorUtil
import com.fenghuajueli.libbasecoreui.constants.AppConfigInfo
import com.fenghuajueli.libbasecoreui.constants.SwitchNetConstants
import com.fenghuajueli.module_user.network.di.RetrofitDiModule
import com.fenghuajueli.module_user.network.model.BlankBackgroundResponse
import com.fenghuajueli.module_user.network.model.NetworkBackgroundResponse
import com.fenghuajueli.module_user.network.model.refund.RefundRequest
import com.fenghuajueli.module_user.network.model.template.NetworkTemplate
import com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactory
import okhttp3.MediaType.Companion.toMediaType
import retrofit2.Retrofit
import retrofit2.http.Body
import retrofit2.http.GET
import retrofit2.http.POST
import retrofit2.http.Path
import retrofit2.http.Query


//后台系统请求接口
//https://ijj-admin.ijianji.cn/api-test/pay-template?app_id=com.scbgbm.iq&template_type=2
private interface BackgroundApi {

    @GET(value = "{environment}/pay-template")
    suspend fun getTemplate(
        @Path("environment") environment: String,
        @Query("app_id") id: String,
        @Query("template_type") type: Int,
    ): NetworkBackgroundResponse<NetworkTemplate>

    @POST(value = "{environment}/user-refund")
    suspend fun postUserRefund(
        @Path("environment") environment: String,
        @Body refundRequest: RefundRequest,
        @Query("timestamp") timestamp: Long,
        @Query("nonce") nonce: String,
    ): BlankBackgroundResponse
}

object BackgroundNetwork {

    private val networkApi = Retrofit.Builder()
        .baseUrl(SwitchNetConstants.BASE_SWITCH_KEY_URL)
        .callFactory(RetrofitDiModule.okHttpCallFactory())
        .addConverterFactory(
            RetrofitDiModule.providesNetworkJson()
                .asConverterFactory("application/json".toMediaType()),
        )
        .build()
        .create(BackgroundApi::class.java)

    suspend fun getTemplate(type: Int): NetworkBackgroundResponse<NetworkTemplate> =
        networkApi.getTemplate(
            if (AppConfigInfo.APP_DEBUG) "api-test" else "api", AppConfigInfo.APPLICATION_ID, type
        )

    suspend fun commitUserRefund(refundRequest: RefundRequest): BlankBackgroundResponse =
        networkApi.postUserRefund(
            environment = if (AppConfigInfo.APP_DEBUG) "api-test" else "api",
            refundRequest = refundRequest,
            timestamp = System.currentTimeMillis(),
            nonce = GeneratorUtil.randomSequence(32)
        )
}